package com.xxl.job.admin.controller;

import com.xxl.job.admin.core.model.XxlJobGroup;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.core.route.ExecutorRouteStrategyEnum;
import com.xxl.job.admin.dao.IXxlJobGroupDao;
import com.xxl.job.admin.dao.IXxlJobInfoDao;
import com.xxl.job.admin.service.IXxlJobService;
import com.xxl.job.core.biz.model.ReturnT;

import org.bigdata.framework.admin.web.controller.BaseContoroller;
import org.bigdata.framework.admin.web.util.DateUtils;
import org.bigdata.framework.core.model.User;
import org.bigdata.framework.core.protocol.IPublicService;
import org.quartz.CronExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * index controller
 * @author xuxueli 2015-12-19 16:13:16
 */
@Controller
//@RequestMapping("/jobinfo")
public class JobInfoController extends BaseContoroller{

	@Autowired
	private IXxlJobGroupDao xxlJobGroupDao;
	@Autowired
	private IXxlJobInfoDao xxlJobInfoDao;
	@Autowired
	private IXxlJobService xxlJobService;
	@Autowired
	private IPublicService publicService;
	
	
	// 任务调度管理页面
	@RequestMapping("xxl-job-info-list.html")
	public String xxljobinfolist() {
		return "/modules/xxljob/xxl_job_info_list";
	}
	// 任务调度管理新增页面
	@RequestMapping("xxl-job-info-add.html")
	public String xxljobinfoadd() {
		return "/modules/xxljob/xxl_job_info_add";
	}
	//任务调度管理列表
	@RequestMapping("xxljob_pageList")
	@ResponseBody
	public void xxljob_pageList(HttpServletRequest request,HttpServletResponse response) throws Exception {
		Integer pageNumber = Integer.parseInt(request.getParameter("pageNumber"));
		String jobHandler = request.getParameter("jobHandler");
		String jobGroup = request.getParameter("jobGroup");
		Integer pageSize = 1;
		//int jobGroup=1;
		//String executorHandler=null;
		if (request.getParameter("page") != null) {
			pageSize = Integer.parseInt(request.getParameter("page"));
		} else {
			pageSize = 1;
		}
		/*
		String queryParam = request.getParameter("queryParams");
		if(queryParam.equals("jobHandler")){
			executorHandler=text;
		}else if(queryParam.equals("actuator")){
			jobHandler=text;
		}else{
		}
		*/
		/*
		List<XxlJobGroup> findAll = xxlJobGroupDao.findAll();
		if(jobHandler!=null){
			for (XxlJobGroup xxlJobGroup : findAll) {
				if(xxlJobGroup.getTitle().equals(jobHandler)){
					jobGroup=Integer.parseInt(xxlJobGroup.getId()+"");
					break;
				}
			}
		}
		*/
		//HashMap<String, Object> queryParams = new HashMap<String, Object>();
		//queryParams.put(queryParam, text);
		Map<String, Object> pageList = xxlJobService.pageList((pageSize-1)*pageNumber, pageNumber, Integer.parseInt(jobGroup), jobHandler, null);
		Integer count  = Integer.parseInt(pageList.get("recordsTotal")+"");
		List<XxlJobInfo> XxlJobInfos = (List<XxlJobInfo>) pageList.get("data");
		for (XxlJobInfo xxlJobInfo : XxlJobInfos) {
			xxlJobInfo.setXxlJobGroup(xxlJobGroupDao.load(xxlJobInfo.getJobGroup()));
		}
		StringBuffer sb = new StringBuffer();
		String result = formatToJson(XxlJobInfos);
		sb.append("{\"listsize\":" + XxlJobInfos.size() + ",");
		sb.append("\"pageSize\":" + (int) Math.ceil(Double.valueOf(count) / pageNumber) + ",");
		sb.append("\"result\":" + result);
		sb.append("}");
		super.pringWriterToPage(sb.toString(), "application/json", response);
	}
	//任务调度管理删除
	@RequestMapping("xxljob_remove")
	@ResponseBody
	public void xxljob_remove(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		String result ="";
		if(id!=null){
			try {
				xxlJobService.remove(Integer.parseInt(id));
				result = "{\"result\":" + "\"ok\"}";
			} catch (Exception e) {
				result = "{\"result\":" + "\"no\"}";
			}
		}
		super.pringWriterToPage(result.toString(), "application/json", response);
	}
	
	//任务调度管理恢复
	@RequestMapping("xxljob_resume")
	@ResponseBody
	public void xxljob_resume(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		String result ="";
		if(id!=null){
			try {
				xxlJobService.resume(Integer.parseInt(id));
				result = "{\"result\":" + "\"ok\"}";
			} catch (Exception e) {
				result = "{\"result\":" + "\"no\"}";
			}
		}
		super.pringWriterToPage(result.toString(), "application/json", response);
	}
	//任务调度管理暂停
	@RequestMapping("xxljob_pause")
	@ResponseBody
	public void xxljob_pause(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		String result ="";
		if(id!=null){
			try {
				xxlJobService.pause(Integer.parseInt(id));
				result = "{\"result\":" + "\"ok\"}";
			} catch (Exception e) {
				result = "{\"result\":" + "\"no\"}";
			}
		}
		super.pringWriterToPage(result.toString(), "application/json", response);
	}
	//任务调度管理执行
	@RequestMapping("xxljob_trigger")
	@ResponseBody
	public void xxljob_trigger(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		String result ="";
		if(id!=null){
			try {
				xxlJobService.triggerJob(Integer.parseInt(id));
				result = "{\"result\":" + "\"ok\"}";
			} catch (Exception e) {
				result = "{\"result\":" + "\"no\"}";
			}
		}
		super.pringWriterToPage(result.toString(), "application/json", response);
	}
	//获取路由策略
	@RequestMapping("xxljob_routeStrategy")
	@ResponseBody
	public void xxljob_routeStrategy(HttpServletRequest request,HttpServletResponse response) throws Exception {
		ExecutorRouteStrategyEnum[] values = ExecutorRouteStrategyEnum.values();
		List<Map<String, String>>routeStrategy=new ArrayList<Map<String,String>>();
		Map<String, String> map=null;
		for (int i = 0; i < values.length; i++) {
			map=new HashMap<String, String>();
			map.put("title", values[i].getTitle());
			map.put("value", values[i]+"");
			routeStrategy.add(map);
		}
		String result = formatToJson(routeStrategy);
		super.pringWriterToPage(result, "application/json", response);
	}
	//获取执行器
	@RequestMapping("xxljob_jobGroup")
	@ResponseBody
	public void xxljob_jobGroup(HttpServletRequest request,HttpServletResponse response) throws Exception {
		List<XxlJobGroup> jobGroupList =  xxlJobGroupDao.findAll();
		String result = formatToJson(jobGroupList);
		super.pringWriterToPage(result, "application/json", response);
	}
	//新增任务
	@RequestMapping("xxljob_add")
	@ResponseBody
	public void xxljob_add(HttpServletRequest request,HttpServletResponse response,XxlJobInfo jobInfo) throws Exception {
		User logUser= publicService.findUser((Integer) request.getSession().getAttribute("userid"));
		jobInfo.setAuthor(logUser.getUsername());
		jobInfo.setAlarmEmail(logUser.getEmail());
		jobInfo.setAddTime(DateUtils.getDate());
		String result ="";
		ReturnT<String> add = xxlJobService.add(jobInfo);
		if(ReturnT.SUCCESS.equals(add)){
			result = "{\"result\":" + "\"ok\"}";
		}else{
			result = "{\"result\":\"" + add.getMsg()+"\"}";
		}
		super.pringWriterToPage(result, "application/json", response);
	}
	//编辑任务
	@RequestMapping("xxljob_reschedule")
	@ResponseBody
	public void xxljob_reschedule(HttpServletRequest request,HttpServletResponse response,XxlJobInfo jobInfo) throws Exception {
		User logUser= publicService.findUser((Integer) request.getSession().getAttribute("userid"));
		jobInfo.setUpdateTime(DateUtils.getDate());
		jobInfo.setAuthor(logUser.getUsername());
		jobInfo.setAlarmEmail(logUser.getEmail());
		String result ="";
		ReturnT<String> reschedule = xxlJobService.reschedule(jobInfo);
		if(ReturnT.SUCCESS.equals(reschedule)){
			result = "{\"result\":" + "\"ok\"}";
		}else{
			result = "{\"result\":\"" +reschedule.getMsg() +"\"}";
		}
		super.pringWriterToPage(result, "application/json", response);
	}
	//编辑任务,初始化
	@RequestMapping("xxljob_editInit")
	@ResponseBody
	public void xxljob_editInit(HttpServletRequest request,HttpServletResponse response,XxlJobInfo jobInfo) throws Exception{
		jobInfo= xxlJobInfoDao.loadById(jobInfo.getId());
		String result = formatToJson(jobInfo);
		super.pringWriterToPage(result, "application/json", response);
	}
	
	/*
	@RequestMapping
	public String index(Model model) {

		// 路由策略-列表
		model.addAttribute("ExecutorRouteStrategyEnum", ExecutorRouteStrategyEnum.values());

		// 任务组
		List<XxlJobGroup> jobGroupList =  xxlJobGroupDao.findAll();
		model.addAttribute("JobGroupList", jobGroupList);
		return "jobinfo/jobinfo.index";
	}
	
	@RequestMapping("/pageList")
	@ResponseBody
	public Map<String, Object> pageList(@RequestParam(required = false, defaultValue = "0") int start,  
			@RequestParam(required = false, defaultValue = "10") int length,
			int jobGroup, String executorHandler, String filterTime) {
		
		return xxlJobService.pageList(start, length, jobGroup, executorHandler, filterTime);
	}
	
	@RequestMapping("/add")
	@ResponseBody
	public ReturnT<String> add(XxlJobInfo jobInfo) {
		return xxlJobService.add(jobInfo);
	}
	
	@RequestMapping("/reschedule")
	@ResponseBody
	public ReturnT<String> reschedule(XxlJobInfo jobInfo) {
		return xxlJobService.reschedule(jobInfo);
	}
	
	@RequestMapping("/remove")
	@ResponseBody
	public ReturnT<String> remove(int id) {
		return xxlJobService.remove(id);
	}
	
	@RequestMapping("/pause")
	@ResponseBody
	public ReturnT<String> pause(int id) {
		return xxlJobService.pause(id);
	}
	
	@RequestMapping("/resume")
	@ResponseBody
	public ReturnT<String> resume(int id) {
		return xxlJobService.resume(id);
	}
	
	@RequestMapping("/trigger")
	@ResponseBody
	public ReturnT<String> triggerJob(int id) {
		return xxlJobService.triggerJob(id);
	}
	*/
}
